//
//  ResetPwdViewController.m
//  LogisticsFollow
//
//  Created by JustFei on 2016/12/18.
//  Copyright © 2016年 manridy. All rights reserved.
//

#import "ResetPwdViewController.h"
#import "ResetPwdTableViewCell.h"
#import "AFNetworking.h"
#import "MBProgressHUD.h"

@interface ResetPwdViewController () < UITableViewDelegate , UITableViewDataSource >

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIButton *sureButton;
@property (nonatomic ,strong) NSArray *nameArr;
@property (nonatomic ,strong) UITextField *oldPwdTextField;
@property (nonatomic ,strong) UITextField *firstNewPwdTextField;
@property (nonatomic ,strong) UITextField *secondNewPwdTextField;
@property (nonatomic ,strong) MBProgressHUD *hud;

@end

@implementation ResetPwdViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [self.tableView registerNib:[UINib nibWithNibName:@"ResetPwdTableViewCell" bundle:nil] forCellReuseIdentifier:@"resetPwdCell"];
    
    self.navigationItem.title = @"修改密码";
    self.navigationController.navigationBar.tintColor = kWhiteColor;
    
    self.tableView.tableFooterView = [[UIView alloc] init];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UITableViewDelegate && UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 3;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ResetPwdTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"resetPwdCell"];
    
    cell.textField.placeholder = self.nameArr[indexPath.row];
    switch (indexPath.row) {
            case 0:
                self.oldPwdTextField = cell.textField;
            break;
            case 1:
                self.firstNewPwdTextField = cell.textField;
            break;
            case 2:
                self.secondNewPwdTextField = cell.textField;
            break;
            
        default:
            break;
    }
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44;
}

#pragma mark - Action
- (IBAction)sureAction:(UIButton *)sender
{
    if ([self.firstNewPwdTextField.text isEqualToString:self.secondNewPwdTextField.text] && ![self.firstNewPwdTextField.text isEqualToString:@""]) {
        if (self.firstNewPwdTextField.text.length >= 6 && self.firstNewPwdTextField.text.length <= 16) {
            // 启动系统风火轮
            [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
            //显示loading
            self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            self.hud.mode = MBProgressHUDModeIndeterminate;
            self.hud.label.text = @"loading";
            //服务器给的域名
            NSString *domainStr = kResetPwdPort;
            
            //假如需要提交给服务器的参数是key＝1,class_id=100
            //创建一个可变字典
            NSMutableDictionary *parametersDic = [NSMutableDictionary dictionary];
            //往字典里面添加需要提交的参数
            NSString *guid = [[NSUserDefaults standardUserDefaults] objectForKey:@"guid"];
            [parametersDic setObject:guid forKey:@"guid"];
            [parametersDic setObject:self.oldPwdTextField.text forKey:@"oldPassword"];
            [parametersDic setObject:self.secondNewPwdTextField.text forKey:@"newPassword"];
            
            AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
            manager.responseSerializer = [AFHTTPResponseSerializer serializer];
            
            //以post的形式提交，POST的参数就是上面的域名，parameters的参数是一个字典类型，将上面的字典作为它的参数
            [manager POST:domainStr parameters:parametersDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                // 隐藏系统风火轮
                [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
                
                //json解析
                NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
                BOOL isSuccess = [[resultDic valueForKey:@"isSuccess"] boolValue];
                if (isSuccess) {
                    [self doSuccessResetPwd];
                }else {
                    [self doFailResetPwd];
                }
                
                NSLog(@"---获取到的json格式的字典--%@",resultDic);
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                [self doFailResetPwd];
                // 解析失败隐藏系统风火轮(可以打印error.userInfo查看错误信息)
                [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
            }];
        }else {
            self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            self.hud.label.text = @"密码需要在6-16位之间";
            self.hud.mode = MBProgressHUDModeText;
            [self.hud hideAnimated:YES afterDelay:1.5];
        }
    }else {
        self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        self.hud.label.text = @"两次输入的密码不同";
        self.hud.mode = MBProgressHUDModeText;
        [self.hud hideAnimated:YES afterDelay:1.5];
    }
}

- (void)doSuccessResetPwd
{
    self.hud.label.text = @"修改成功";
    [self.hud hideAnimated:YES afterDelay:1];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.navigationController popViewControllerAnimated:YES];
    });
}

- (void)doFailResetPwd
{
    self.hud.label.text = @"修改失败，请检查密码是否正确";
    [self.hud hideAnimated:YES afterDelay:1];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.oldPwdTextField resignFirstResponder];
    [self.firstNewPwdTextField resignFirstResponder];
    [self.secondNewPwdTextField resignFirstResponder];
}

#pragma mark - 懒加载
- (NSArray *)nameArr
{
    if (!_nameArr) {
        _nameArr = @[@"请输入旧密码",@"新密码（6-16个字符，区分大小写）",@"确认新密码（6-16个字符，区分大小写）"];
    }
    
    return _nameArr;
}


@end
